import React from 'react'
import { connect } from 'react-redux'

import BaseHomePage from 'src/pageP/home/home-page/index'
import PersonCell from 'src/components/person-cell/index'
import CustomButton from 'src/components/button/CustomButton'
import { inRecruitPostNameCategoryList, homePersonRequest } from 'src/utils/RequestAPI'
import { B_HOME_REFRESH } from 'src/pageB/tabbar'
import { DeviceEventEmitter } from 'react-native'
import RefreshState from 'src/components/custom-flat-list/RefreshState'
import { DismissLoading, ShowLoading } from 'src/utils/ToastUtil'

const mapActiontoProps = dispatch => ({})

@connect(
  ({ landmark, BMineCenterStore, userinfo }) => ({
    landmark,
    BMineCenterStore,
    userinfo,
    userinfoB: userinfo.B,
    userId: userinfo.userId
  }),
  mapActiontoProps
)
class HomePage extends BaseHomePage {
  constructor (props) {
    super(props)
    this.pageType = 'B'
    this.pageKey = 'pageNum'
    this.cityNameKey = 'jobPlace'
    this.categoryKey = 'workCategory'
    this.areaKey = 'workPlace'
    this.orderKey = 'sortType'
    this.homeListParams = [
      {
        [this.pageKey]: 1,
        workNature: ['兼职'],
        pageSize: 10
      },
      {
        [this.pageKey]: 1,
        workNature: ['实习'],
        pageSize: 10
      },
      {
        [this.pageKey]: 1,
        workNature: ['全职'],
        pageSize: 10
      }
    ]
    this.orderLabel = [
      {
        isAll: true,
        label: '推荐人才',
        type: this.orderKey,
        value: 1
      },
      {
        isAll: false,
        label: '最近发布',
        type: this.orderKey,
        value: 1
      }
    ]
    this.withPostCategory = [[], [], []]
  }

  componentWillFocus () {
    this.changeRefresh()
  }

  /**
   * 变化刷新
   */
  changeRefresh ({ postSameCallBack, notPostCallBack ,noCompanyIdCallBack} = {}) {
    const { BMineCenterStore: { haveCompanyApply: { companyId: thisCompanyId } }, userId } = this.props
    console.info('pageB,componentWillFocus', userId, thisCompanyId)
    if (thisCompanyId) {
      const withCurrentPostCategory = this.withPostCategory[this.currentIndex]
      this.initInRecruitPostCategoryByType(thisCompanyId).then(() => {
        if (this.withPostCategory[this.currentIndex].length > 0) { // 有职位，判断是否是一致的
          if (withCurrentPostCategory.length > 0) {
            const beforePost = withCurrentPostCategory[0].content.find((item) => {
              return item.isDefault
            })
            const afterPost = this.withPostCategory[this.currentIndex][0].content.find((item) => {
              return item.isDefault
            })
            if (beforePost.postId !== afterPost.postId) { // 不同
              this._setFilterRefreshByDefault()
            } else {
              postSameCallBack && postSameCallBack()
            }
          } else {
            this._setFilterRefreshByDefault()
          }
        } else { // 没有
          if (withCurrentPostCategory.length > 0) {
            this._setPFilterText({ label: '职位', fullLabel: '' }, () => {
              this._deleteHomeListParams(this.categoryKey)
              this._onRequestRefresh()
            })
          } else {
            notPostCallBack && notPostCallBack()
          }
        }
      })
    } else {
      noCompanyIdCallBack && noCompanyIdCallBack()
    }
  }

  /**
   * 设置过滤文字并且刷新
   * @private
   */
  _setFilterRefreshByDefault = () => {
    const { userId } = this.props
    const firstP = this.withPostCategory[this.currentIndex][0]['content'].find((item) => {
      return item.isDefault
    })
    this._setPFilterText(firstP, () => {
      // this.homeListParams[this.currentIndex].userId = userId
      this.homeListParams[this.currentIndex][this.categoryKey] = firstP.value
      this._onRequestRefresh()
    })
  }

  /**
   * 设置过滤文字并且刷新
   * @private
   */
  _setFilterRefresh = () => {
    const { userId } = this.props
    const firstP = this.withPostCategory[this.currentIndex][0]['content'][0]
    this._setPFilterText(firstP, () => {
      // this.homeListParams[this.currentIndex].userId = userId
      this.homeListParams[this.currentIndex][this.categoryKey] = firstP.value
      this._onRequestRefresh()
    })
  }

  snapshotBeforeUpdate (prevProps, prevState) {
    if (prevProps.userId !== this.props.userId && !this.props.userId) { // 退出登录
      console.info('pageB,snapshotBeforeUpdate', prevProps, this.props)
      this.withPostCategory = [[], [], []]
      this._setInitPFilterText()
    }
  }

  _setInitPFilterText = () => {
    this._setPFilterText({ label: '职位', fullLabel: '' }, () => {
      this._deleteHomeListParams(this.categoryKey)
      this._onRequestRefresh()
    })
  }

  componentDidMount () {
    this._getAreaListByCityName()
    this._initIndustryCategory()
    const { userId } = this.props
    if (!userId) {
      this._onRequestRefresh()
    }
    this.tabRefreshSubscription = DeviceEventEmitter.addListener(
      B_HOME_REFRESH,
      this.tabRefreshClick
    )
    this.companyIdChangedSub = DeviceEventEmitter.addListener('companyIdChanged', (companyId) => {
      console.info('pageB,deviceEvent', companyId)
      const { BMineCenterStore: { haveCompanyApply: { companyId: thisCompanyId } } } = this.props
      if (thisCompanyId !== companyId) {
        this.initRequestRefresh(companyId)
      }
    })
  }

  initRequestRefresh (companyId) {
    const { userId } = this.props
    console.info('pageB,deviceEventRequest', companyId)
    this.initInRecruitPostCategoryByType(companyId).then(() => {
      if (this.withPostCategory[this.currentIndex].length > 0) { // 有发布的岗位
        this._setFilterRefreshByDefault()
      } else { // 没有发布的岗位
        // this.homeListParams[this.currentIndex].userId = userId
        this._onRequestRefresh()
      }
    })
  }

  _setPFilterText = (params, callback) => {
    this.tabScroll[this.currentIndex].filterArr[1].label = params.firstLabel || params.label
    this.tabScroll[this.currentIndex].filterArr[1].fullLabel = params.label
    this.setState({
      filterArr: [...this.tabScroll[this.currentIndex].filterArr]
    }, callback)
  }

  componentWillUnmount () {
    super.componentWillUnmount()
    this.tabRefreshSubscription && this.tabRefreshSubscription.remove()
    this.companyIdChangedSub && this.companyIdChangedSub.remove()
    console.log('B---->HomePage--->componentWillUnmount')
  }

  /**
   * 获取正在热招的数据
   * @param companyId
   */
  async initInRecruitPostCategory (companyId) {
    for (let i = 0; i < this.withPostCategory.length; i++) {
      let typeValue = 0
      if (i === 1) {
        typeValue = 2
      } else if (i === 2) {
        typeValue = 1
      }
      const result = await inRecruitPostNameCategoryList({
        headers: { companyId },
        params: { type: typeValue }
      })
      this.withPostCategory[i] = result.data && result.data.length > 0 ? this._getPostCategories(result.data) : []
    }
  }

  /**
   * 获取正在热招的数据
   * @param companyId
   */
  initInRecruitPostCategoryByType (companyId) {
    ShowLoading()
    return new Promise((resolve) => {
      inRecruitPostNameCategoryList({
        headers: { companyId },
        params: { type: this._getPostType() }
      }).then((result) => {
        this.withPostCategory[this.currentIndex] = result.data && result.data.length > 0 ? this._getPostCategories(result.data) : []
        resolve('成功')
      }).finally(() => {
        DismissLoading()
      })
    })
  }

  _getPostType = () => {
    switch (this.currentIndex) {
      case 0:
        return 0
      case 1:
        return 2
      case 2:
        return 1
    }
  }

  _getPostCategories = (data) => {
    return [
      // {
      //   title: '全部',
      //   content: [{
      //     isAll: true,
      //     label: '全部',
      //     type: this.categoryKey,
      //     value: this.categoryKey
      //   }]
      // },
      {
        title: '正在招聘',
        content: data.map((item) => {
          return {
            isAll: false,
            firstLabel: item.category,
            label: `${item.name}•${item.category}`,
            type: this.categoryKey,
            value: [item.category],
            postId: item.postId,
            isDefault: item.isDefault,
            postType: this._getPostType()
          }
        })
      }
    ]
  }

  tabRefreshClick = () => {
    if (this.scrollableTabRef) {
      this._scrollToOffset(0, false)
      this.scrollableTabRef.beginHeaderRefresh(RefreshState.Idle)
    }
  }

  postFunc () {
    return homePersonRequest
  }

  renderItem ({ item, index }) {
    return (
      <CustomButton params={{ item, index }} onPress={this._personClick}>
        <PersonCell index={index} item={item}/>
      </CustomButton>
    )
  }

  _personClick = ({ item, index }) => {
    console.info(item, index)
    this.props.navigation.navigate('CResumeDetail', {
      userId: item.userId,
      type: this.currentIndex
    })
  }
}

export default HomePage

// https://github.com/Micjoyce/ScrollViewWithTabView
// https://snack.expo.io/@satya164/collapsible-header-with-tabview
// https://snack.expo.io/By0FEomKf
